package cn.edu.dgut.css.sai.lab2demo;

import ch.qos.logback.classic.Logger;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.beans.factory.BeanFactory;


public class AbstractApplicationContext {
    public static final String APPLICATION_EVENT_MULTICACASTER_BEAN_NAME = "applicationEventMulticaster";
    private ApplicationEventMulticaster applicationEventMulticaster;
    private ApplicationContext applicationContext;

    protected void initApplicationEventMulticaster(){
        ConfigurableApplicationContext context = (ConfigurableApplicationContext)applicationContext;
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        Logger logger = null;
        if(beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICACASTER_BEAN_NAME)){
            this.applicationEventMulticaster=
                    beanFactory.getBean(APPLICATION_EVENT_MULTICACASTER_BEAN_NAME, ApplicationEventMulticaster.class);
            if(logger.isTraceEnabled()){
                logger.trace("Using ApplicationEventMulticaster["+this.applicationEventMulticaster+"]");
            }
        }
        else{
            this.applicationEventMulticaster=new SimpleApplicationEventMulticaster(beanFactory);
            beanFactory.registerSingleton(APPLICATION_EVENT_MULTICACASTER_BEAN_NAME,this.applicationEventMulticaster);
            if(logger.isTraceEnabled()){
                logger.trace("No '"+APPLICATION_EVENT_MULTICACASTER_BEAN_NAME+"'bean,using"+
                        "["+this.applicationEventMulticaster.getClass().getSimpleName()+"]");
            }
        }
    }
}
